#!/bin/sh

iptables -D INPUT -p tcp --dport 1723 -m comment --comment "Rule For PPTP VPN Server" -j ACCEPT 2> /dev/null
pptp_nums=`iptables -t nat -L POSTROUTING 2> /dev/null|grep -c "Rule For PPTP VPN Server"`
if [ -n "$pptp_nums" ]; then
	until [ "$pptp_nums" = 0 ]
	do
		pptp_rules=`iptables -t nat -L POSTROUTING --line-num 2> /dev/null|grep "Rule For PPTP VPN Server" |awk '{print $1}'`
		for pptp_rule in $pptp_rules
		do
			iptables -t nat -D POSTROUTING $pptp_rule 2> /dev/null
			break
		done
		pptp_nums=`expr $pptp_nums - 1`
	done
fi
nums=`iptables -L forwarding_rule 2> /dev/null|grep -c "Rule For PPTP VPN Server"`
if [ -n "$nums" ]; then
	until [ "$nums" = 0 ]
	do
		rules=`iptables -L forwarding_rule --line-num 2> /dev/null|grep "Rule For PPTP VPN Server" |awk '{print $1}'`
		for rule in $rules
		do
			iptables -D forwarding_rule $rule 2> /dev/null
			break
		done
		nums=`expr $nums - 1`
	done
fi

enable=$(uci get pptpd.pptpd.enabled)
if [ $enable -eq 1 ]; then
	is_nat=$(uci get pptpd.pptpd.is_nat)
	if [ "$is_nat" -eq 1 ];then
		localip=$(uci get pptpd.pptpd.localip)
		export_interface=$(uci get pptpd.pptpd.export_interface)
		if [ "$export_interface" != "default" ];then
			iptables -t nat -I POSTROUTING -s ${localip%.*}.0/24 -o ${export_interface} -m comment --comment "Rule For PPTP VPN Server" -j MASQUERADE
		else
			iptables -t nat -I POSTROUTING -s ${localip%.*}.0/24 -m comment --comment "Rule For PPTP VPN Server" -j MASQUERADE
		fi
		iptables -I forwarding_rule -s ${localip%.*}.0/24 -m comment --comment "Rule For PPTP VPN Server" -j ACCEPT
	fi
	iptables -I INPUT -p tcp --dport 1723 -m comment --comment "Rule For PPTP VPN Server" -j ACCEPT 2>/dev/null
fi
